/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package com.home.gui;



import com.home.common.ApplicationCommon;
import com.home.common.Constants;
import com.home.common.Role;
import com.home.components.ModalJInternalFrame;
import com.home.dao.AgentDao;
import com.home.logic.AccountLogic;
import com.home.logic.AgentLogic;
import com.home.main.SCORECARD;
import com.home.mapping.Account;
import com.home.mapping.Agent;
import java.awt.Dimension;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.event.KeyEvent;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingWorker;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;

/**
 *
 * @author vi
 */
public class Login extends ModalJInternalFrame {

    /**
     * Creates new form Login
     */
    public Login(MainScreen mainPanel) {
        initComponents();
        // set position center
        this.mainPanel = mainPanel;
       
        this.setModal(true);
        setBounds(ApplicationCommon.getRectangleForCenter(mainPanel.getSize().width, mainPanel.getSize().height, this.getWidth(), this.getHeight()));
        checkRemember();
        loadRemember();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        txtUserName = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        btnLogin = new javax.swing.JButton();
        btnReset = new javax.swing.JButton();
        txtPassword = new javax.swing.JPasswordField();
        chkRemember = new javax.swing.JCheckBox();

        setClosable(true);
        setTitle("Login");

        jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/icon/login_form.png"))); // NOI18N

        jLabel2.setFont(new java.awt.Font("Tahoma", 1, 36)); // NOI18N
        jLabel2.setForeground(new java.awt.Color(102, 102, 102));
        jLabel2.setText("LOGIN");

        jLabel3.setText("User Name");

        jLabel4.setText("Password");

        btnLogin.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/icon/btn_login.png"))); // NOI18N
        btnLogin.setText("Login");
        btnLogin.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnLoginActionPerformed(evt);
            }
        });

        btnReset.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/icon/btn_reset.png"))); // NOI18N
        btnReset.setText("Reset");
        btnReset.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnResetActionPerformed(evt);
            }
        });

        txtPassword.setToolTipText(null);
        txtPassword.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txtPasswordKeyPressed(evt);
            }
        });

        chkRemember.setText("Remember Me");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 105, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(54, 54, 54)
                        .addComponent(jLabel2))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addComponent(jLabel3)
                                .addGap(18, 18, 18))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel4)
                                .addGap(24, 24, 24)))
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(chkRemember)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                .addGroup(layout.createSequentialGroup()
                                    .addComponent(btnReset)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                    .addComponent(btnLogin))
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addComponent(txtUserName, javax.swing.GroupLayout.DEFAULT_SIZE, 217, Short.MAX_VALUE)
                                    .addComponent(txtPassword))))))
                .addContainerGap(15, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel3)
                            .addComponent(txtUserName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel4)
                            .addComponent(txtPassword, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(chkRemember))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(38, 38, 38)
                        .addComponent(jLabel1)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnReset)
                    .addComponent(btnLogin))
                .addContainerGap(22, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnResetActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnResetActionPerformed
        reset();
    }//GEN-LAST:event_btnResetActionPerformed

    private void btnLoginActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnLoginActionPerformed
        String userName = txtUserName.getText();
        String password = String.valueOf(txtPassword.getPassword());
        
        Account account = new AccountLogic().findAccountForLogin(userName, password);
        
        if (account.getIdAccount() == null) {
            JOptionPane.showMessageDialog(this, "Wrong username or password !");
            reset();
        } else {
            //Agent agent = new AgentLogic().findAgentById(account.getAgent().getIdAgent());
            Agent agent = account.getAgent();
            if (agent.getRole() == Role.ROLE_QA) {
                mainPanel.setAgentLogin(agent);
                mainPanel.setRole(agent.getRole());
                mainPanel.setAccountLogin(account);
                mainPanel.fillInfo(agent.getAgentName(), agent.getTeam().getTeamName(), agent.getTeam().getVenture().getVentureName());
                mainPanel.afterLogin();
                if (chkRemember.isSelected()) {
                    saveRemember(txtUserName.getText());
                } else {
                    saveRemember("");
                }
                this.dispose();
                if (agent.getRole() == Role.ROLE_QA) {
                    final WaitingDialog loadingDialog = new WaitingDialog(mainPanel, true);
                    SwingWorker<?, ?> worker = new SwingWorker<Void, Void>() {
                        @Override
                        protected Void doInBackground() throws Exception {
                            mainPanel.addNewInternalFrame(new QAWorkingList(mainPanel));
                            return null;
                        }

                        @Override
                        protected void done() {
                            loadingDialog.dispose();
                        }
                    };
                    worker.execute();
                    loadingDialog.setVisible(true);
                }
            } else {
                JOptionPane.showMessageDialog(this, "Please login with QA role !");
                reset();
            }
        }
    }//GEN-LAST:event_btnLoginActionPerformed

    private void txtPasswordKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtPasswordKeyPressed
        // TODO add your handling code here:
        int key = evt.getKeyCode();
        if (key == KeyEvent.VK_ENTER) {
            btnLoginActionPerformed(null);
        }
    }//GEN-LAST:event_txtPasswordKeyPressed


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnLogin;
    private javax.swing.JButton btnReset;
    private javax.swing.JCheckBox chkRemember;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JPasswordField txtPassword;
    private javax.swing.JTextField txtUserName;
    // End of variables declaration//GEN-END:variables
    private MainScreen mainPanel;
    
    private void reset() {
        txtUserName.requestFocus();
        txtUserName.setText("");
        txtPassword.setText("");
    }
    
    private void checkRemember() {
        File f = null;
        try {
            f = new File(Constants.PATH_FOLDER_CONFIG);
            if (!f.exists()) {
                FileUtils.forceMkdir(f);
                File file = new File(Constants.PATH_FOLDER_CONFIG + Constants.NAME_FILE_CONFIG);
                boolean createFile = file.createNewFile();
//                if (createFile) {
//                    //InputStream in = SCORECARD.class.getClassLoader().getResourceAsStream(Constants.SOURCE_FILE_CONFIG);
//                    // copy file from aptech/semester/code/conn/config.properties to folder has created
//                    //FileUtils.copyInputStreamToFile(in, file);
//                    OutputStream output = new FileOutputStream("config.properties");
//                }
            }
            
        } catch (Exception e) {
            e.printStackTrace();
            return;
        }
    }
    
    private void loadRemember() {
        
        Properties prop = new Properties();
    	InputStream input = null;
        try {
            String filename = Constants.PATH_FOLDER_CONFIG + Constants.NAME_FILE_CONFIG;
            File f = new File(filename);
            input = new FileInputStream(f);
            
            if (input == null) {
                System.out.println("Sorry, unable to find " + filename);
                
            } else {
                prop.load(input);
                           
                String userName = prop.getProperty("username");
                
                                
                txtUserName.setText(userName);
                
                if (!StringUtils.isBlank(userName)) {
                    chkRemember.setSelected(true);
                }
                
            }
         
        } catch(IOException e) {
            
        }
    }
    
    private void saveRemember(String username) {
        Properties prop = new Properties();
        OutputStream output = null;

        try {
            String filename = Constants.PATH_FOLDER_CONFIG + Constants.NAME_FILE_CONFIG;
            File f = new File(filename);

            if (!f.exists()) {
                f.createNewFile();
            }

            output = new FileOutputStream(f);

                // set the properties value
            prop.setProperty("username", username);

            // save properties to project root folder
            prop.store(output, null);

        } catch (IOException io) {
            io.printStackTrace();
        } catch (Exception io) {

        } finally {
            if (output != null) {
                try {
                    output.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
    }
}
